using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Ltf.Remoting.Operations;
using Ltf.Remoting.TeamFoundation;

namespace Ltf.Diffs.MergeCommands
{
	public class MergeFileChangesCommand : MergeCommand
	{
		public MergeFileChangesCommand(TFServerConnection connection, string targetFile, string diffResults, bool isManualOnly)
		{
			this.Connection = connection;
			this.diffResults = diffResults;
			this.TargetFile = targetFile;
			this.isManualOnly = isManualOnly;
		}

		private string diffResults;

		public string DiffResults
		{
			get { return diffResults; }
			set { diffResults = value; }
		}

		private bool isManualOnly;

		public bool IsManualOnly
		{
			get { return isManualOnly; }
			set { isManualOnly = value; }
		}

		public override MergeResult Execute()
		{
			Ltf.Diffs.Diff3Docs.Output output = new Ltf.Diffs.Diff3Docs.Output(TargetFile);
			Diff3Results d3Results = new Diff3Results(DiffResults);

			output.LoadResults(d3Results);

			if (output.NumberOfConflicts == 0)
			{
				// get read of any pesky readonly flags, lizard has no respect for readonly flags!
				File.SetAttributes(TargetFile, (File.GetAttributes(TargetFile) | FileAttributes.ReadOnly) ^ FileAttributes.ReadOnly);
				File.WriteAllText(TargetFile, output.GetAllText());


				WorkspaceOperators wso = GetWorkspaceOperators();
				if (wso != null)
				{
					wso.PendEdit(new string[] { TargetFile });
				}
				return new MergeResult(1, 0, 0, 0, 0, 0);
			}
			return new MergeResult(0, 0, 0, 0, 0, 0);
		}

		public override void Validate()
		{
			if (!File.Exists(TargetFile))
				throw new MergeException(string.Format("Target file '{0}' does not exist.", TargetFile));
		}

		public override string ShortName
		{
			get
			{
				if (isManualOnly)
					return "Manual Merge";
				else
					return "Merge";
			}
		}
	}
}
